package com.neudu.yiyang.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.neudu.yiyang.commons.JSONReturn;
import com.neudu.yiyang.utils.TokenUtils;
import com.neudu.yiyang.pojo.User;
import com.neudu.yiyang.service.MenuService;
import com.neudu.yiyang.service.UserService;
import com.neudu.yiyang.utils.FLAGS;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
public class UserController {
    @Autowired
    JSONReturn jsonReturn;

    @Autowired
    MenuService menuService;


    @Autowired
    UserService userService;

    @Autowired
    TokenUtils tokenUtils;
    @PostMapping("/register")
    public String register(@RequestBody User user) {
        try {
            // 检查用户名是否已存在
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUsername, user.getUsername());
            List<User> existingUsers = userService.list(queryWrapper);
            if (existingUsers != null && !existingUsers.isEmpty()) {
                return jsonReturn.returnFailed("用户名已存在");
            }

            // 设置创建时间和更新时间
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());
            user.setIsDeleted(0); // 默认未删除

            // 插入用户
            boolean result = userService.save(user);
            if (result) {
                return jsonReturn.returnSuccess("注册成功");
            } else {
                return jsonReturn.returnFailed("注册失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }
    @RequestMapping("login")
    public String login(User user, HttpServletRequest request){
        try {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUsername, user.getUsername())
                    .eq(User::getPassword, user.getPassword())
                    .select(User::getId, User::getNickname, User::getUsername, User::getRoleId);
            List<User> users = userService.list(queryWrapper);
            System.out.println(users);

            if (users != null && users.size() > 0){
                User loginuser = users.get(0);
                loginuser.setToken(tokenUtils.getToken());
                return jsonReturn.returnSuccess(loginuser);
            } else {
                return jsonReturn.returnFailed(FLAGS.LOGIN_FAIL);
            }
        } catch(Exception e){
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    //获取菜单：当前项目是角色决定菜单，所以查询条件是角色id
    @RequestMapping("getmenus")
    public String getMenusByRoleId(Integer roleid){
        try {
            return jsonReturn.returnSuccess(menuService.getByroleid(roleid));
        } catch (Exception e){
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }
    // 查询用户信息
    @RequestMapping("listusers")
    public String getByConditions(User conds) {
        try {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(!ObjectUtils.isEmpty(conds.getUsername()), User::getUsername, conds.getUsername())
                    .eq(!ObjectUtils.isEmpty(conds.getPassword()), User::getPassword, conds.getPassword())
                    .eq(!ObjectUtils.isEmpty(conds.getId()), User::getId, conds.getId())
                    .like(!ObjectUtils.isEmpty(conds.getNickname()), User::getNickname, conds.getNickname())
                    .eq(!ObjectUtils.isEmpty(conds.getPhoneNumber()), User::getPhoneNumber, conds.getPhoneNumber())
                    .eq(!ObjectUtils.isEmpty(conds.getSex()), User::getSex, conds.getSex())
                    .select(User::getId, User::getNickname, User::getUsername, User::getRoleId);
            List<User> users = userService.list(queryWrapper);
            return jsonReturn.returnSuccess(users);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    // 添加用户
    @RequestMapping("adduser")
    public String addOne(User user) {
        try {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUsername, user.getUsername());
            List<User> users = userService.list(queryWrapper);

            if (users != null && users.size() > 0) {
                return jsonReturn.returnFailed("添加失败：登录名重复！");
            }

            userService.save(user);
            return jsonReturn.returnSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    // 更新用户
    @RequestMapping("modifyuser")
    public String modifyOne(User user) {
        try {
            if (user == null || user.getId() == null) {
                return jsonReturn.returnFailed("更新失败：未能获取用户信息！");
            }

            userService.updateById(user);
            return jsonReturn.returnSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    // 删除用户
    @RequestMapping("removeuser")
    public String removeOne(Integer id) {
        try {
            if (id == null) {
                return jsonReturn.returnFailed("删除失败：未能获取用户信息！");
            }

            userService.removeById(id);
            return jsonReturn.returnSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    @PostMapping("/get_user_list")
    public String getUserList(@RequestBody Map<String, String> request) {
        try {
            String keyword = request.get("keyword");
            QueryWrapper<User> userWrapper = new QueryWrapper<>();
            if (keyword != null && !"".equals(keyword)) {
                userWrapper.like("username", keyword);
            }
            List<User> userList = userService.list(userWrapper);
            return jsonReturn.returnSuccess(userList);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    @PostMapping("/edit_user")
    public String editUser(@RequestBody User user) {
        try {
            boolean result = userService.updateById(user);
            if (result) {
                return jsonReturn.returnSuccess("用户信息更新成功");
            } else {
                return jsonReturn.returnError("用户信息更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("操作失败：" + e.getMessage());
        }
    }

    @PostMapping("/delete_user")
    public String deleteUser(@RequestBody Map<String, Integer> request) {
        try {
            Integer userId = request.get("id");
            if (userId == null || userId <= 0) {
                return jsonReturn.returnError("无效的用户ID");
            }
            boolean result = userService.removeById(userId);
            if (result) {
                return jsonReturn.returnSuccess();
            } else {
                return jsonReturn.returnError("删除用户失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }
}
